import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    // const request = ctx.getRequest();
    // const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
    let code = HttpStatus.INTERNAL_SERVER_ERROR;
    let message: any = '服务器错误';
    if (exception instanceof HttpException) {
      code = exception.getStatus();
      message = exception.message;
    } else if (exception instanceof Error) {
      message = exception.message;
    } else if (exception instanceof Object) {
      message = JSON.stringify(exception);
    } else if (exception instanceof String) {
      message = exception;
    } else {
      message = exception;
    }
    response.status(HttpStatus.OK).json({ code, message });
  }
}
